import { createRouter, createWebHashHistory } from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import Register from '../views/ForgotPassword.vue'
import QuickLogin from '../views/QuickLogin.vue'
import { enterLogin, enterMain } from '@/tool'
import ImagePreview from '../views/ImagePreview.vue'
// image - preview   需要一个图片预览页面
const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: "/forgot",
    name: "ForgotPassword",
    component: Register
  },
  {
    path: "/quick",
    name: "QuickLogin",
    component: QuickLogin
  },
  {
    path: "/preview",
    name: "ImagePreview",
    component: ImagePreview
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

const whiteList = [
  'ForgotPassword',
  "Changeword",
  "QuickLogin",
  "ImagePreview"
]

const Token = window.localStorage.getItem('Token')
const paths = routes.map(r => whiteList.includes(r.name) && r.path)
const loaction = window.location.href
const pass = paths.findIndex(r => loaction.includes(r))
if (Token && pass < 0) {
  router.isReady().then(async () => {
    const autoState = await window.electronAPI.getLoginItemSettings()
    if (autoState.openAtLogin) {
      enterMain()
      router.replace('/')
    } else {
      enterLogin()
      router.replace('/quick')
    }
  })
}

router.beforeEach(async (to, from, next) => {
  if (to.path === '/login') return next()
  const Token = window.localStorage.getItem('Token')
  if (!Token) {
    if (whiteList.includes(to.name)) return next()
    router.replace('/login')
    enterLogin()
  }
  next()
})

export default router
